import Taro, { Component } from '@tarojs/taro'
import { View, Text, Textarea, Input, Picker, PickerView, PickerViewColumn, Icon } from '@tarojs/components'
import './wantToFinance.scss'

export default class Wanttofinance extends Component {

  config = {
    navigationBarTitleText: '我要融资'
  }

  componentDidMount (e) { 
    const user=Taro.getStorageSync("currentCustomer")
    this.setState({
      customerId:user.id,
      customerName:user.customerName,
      orgCode:user.orgCode

    })
  }

  state={
    //界面显示
    customerName: "天诚粮食制品有限公司",
    orgCode: "321323000008045",
    financingAmount: '￥1,000',
    customerId: "1",      //企业编号
    loanRateUpper: "6.00%",  
    loanRateLower: "4.00%",
    
    //时间选择器应当显示的值
    selectTimeStr:"1-6个月",
    selectModeStr:"抵押",
    selectPurpose:"",
    selectBank:[
      {id:0, name:"中国建设银行",selected:true},
      {id:1, name:"中国工商银行",selected:true},
      {id:2, name:"中国农业银行",selected:false},
      {id:3, name:"江苏银行",selected:false},
    ],
    selectBankTemp:[
      {id:0, name:"中国建设银行",selected:true},
      {id:1, name:"中国工商银行",selected:true},
      {id:2, name:"中国农业银行",selected:false},
      {id:3, name:"江苏银行",selected:false},
    ]
  }


  //清除文字中的某个字符 可以直接使用字符串替换  var replaceStr=mystr.replace("zifuchuan"," ");


  /* 处理融资目的输入 */
  purpose=""
  handlePurposeInput(e){
    this.purpose=e.detail.value;
  }

  /* 处理融资金额输入 */
  financingAmount=1000
  handleFinanceMoneyInputFocus(e){
    this.setState({
      financingAmount:this.financingAmount
    })
  }
  handleFinanceMoneyInput(e){
    // console.log(e.detail.value)
    this.financingAmount=e.detail.value;
  }
  handleFinanceMoneyInputBlur(e){
    //将this.financeNeed.financingAmount 转变成 this.state.financingAmount
    let financingAmount = this.financingAmount;
    financingAmount=financingAmount.toString();
    let str="";
    for(let i=0;i<financingAmount.length;i++){
      str=financingAmount[financingAmount.length-i-1]+str;
      if(i%3===2){str=','+str;}
    }
    if(str[0]===','){str=str.substr(1)};
    if(str==='')str='0'
    financingAmount='￥'+str;
    this.setState({financingAmount})

  }

  /* 处理利率输入 */
  loanRateLower=4.00
  loanRateUpper=6.00
  handleRateLowerInputFocus(e){
    this.setState({
      loanRateLower:this.loanRateLower
    })
  }
  handleRateUpperInputFocus(e){
    this.setState({
      loanRateUpper:this.loanRateUpper
    })
  }
  handleRateLowerInput(e){
    this.loanRateLower=e.detail.value;
  }
  handleRateUpperInput(e){
    this.loanRateUpper=e.detail.value;
  }
  handleRateLowerInputBlur(e){
    let {loanRateLower}=this;
    loanRateLower=loanRateLower.toString();
    if(loanRateLower==='')loanRateLower=0
    loanRateLower+="%"
    this.setState({loanRateLower})
  }
  handleRateUpperInputBlur(e){
    let {loanRateUpper}=this;
    loanRateUpper=loanRateUpper.toString();
    if(loanRateUpper==='')loanRateUpper=0
    loanRateUpper+="%"
    this.setState({loanRateUpper})
  }

  /* 处理备注信息的输入 */
  remark=null
  handleRemarkInput(e){
    this.remark=e.detail.value
  }

  //用来切换选择项
  financeNeed={
    //用来切换选择项
    selectTime:false,
    selectMode:false,
    selectPurpose:false,
    selectInsititution:false,
  }
  /* 关闭所有的选择框 */
  handleCloseAllSelect(e){
    this.setState({
      selectTime:false,
      selectMode:false,
      selectPurpose:false,
      selectInsititution:false
    })
  }

  /* 选择融资期限 */
  selectTimeStr="1-6个月";   //设置一个全局变量 记录选择时间信息
  handleSelectFinanceTime(e){
    this.selectTimeStr="1-6个月";
    //console.log(e)
    this.setState({
      selectTime:true,
      selectMode:false,
      selectPurpose:false,
      selectInsititution:false
    })
  }
  handleSelectFinanceTimeChange(e){
    //获取选择的值
    const id = e.detail.value[0];
    if(id===0){
      this.selectTimeStr="1-6个月";
    }else if(id===1){
      this.selectTimeStr="7-12个月";
    }else if(id===2){
      this.selectTimeStr="13-24个月";
    }
    //this.setState({selectTimeStr})
  }
  handleFinishSelectFinanceTime(){
    this.setState({selectTimeStr:this.selectTimeStr})
    this.handleCloseAllSelect();

  }

  /* 选择担保方式 */
  selectModeStr="抵押"
  ModeStr=["抵押","质押","信保","一般保证","信用"]
  handleSelectMode(e){
    //console.log(e)
    this.selectModeStr="抵押";
    this.setState({
      selectTime:false,
      selectMode:true,
      selectPurpose:false,
      selectInsititution:false
    })
  }
  handleSelectModeChange(e){
    const id = e.detail.value[0];
    // console.log(this.ModeStr[id])
    this.selectModeStr=this.ModeStr[id]
  }
  handleFinishSelectMode(){
    this.setState({selectModeStr:this.selectModeStr})
    this.handleCloseAllSelect();
  }

  /* 选择融资用途 */
  handleSelectPurpose(e){
    //console.log(e)
    this.setState({
      selectTime:false,
      selectMode:false,
      selectPurpose:true,
      selectInsititution:false
    })
  }
  /* 选择金融机构 */
  handleSelectInsititution(e){
    //console.log(e)
    this.setState({
      selectTime:false,
      selectMode:false,
      selectPurpose:false,
      selectInsititution:true
    })
  }
  handleSelectBankClick(e){
    const id=e.target.dataset.index
    let{selectBankTemp}=this.state;
    selectBankTemp.map(b=>{
      if(b.id===id)b.selected=!b.selected;
    })
    this.setState({
      selectBankTemp
    })
  }
  handleFinishAllSelect(e){
    let{selectBankTemp}=this.state;
    this.setState({
      selectBank:selectBankTemp
    })
    this.handleCloseAllSelect()
  }

  //发布融资需求
  handleFinanceNeedPublish(){
    // Taro.setStorageSync("currentCustomer",{
    //   "id":"2","customerName":"五洋集团有限公司","orgCode":"320585000030424"
    // })
    const currentCustomer=Taro.getStorageSync("currentCustomer");
    let {customerName,orgCode}=currentCustomer
    let {financingAmount,loanRateLower,loanRateUpper,remark,purpose}=this;
    let loanTerm=this.state.selectTimeStr;
    let guaranteeMode=1;
      const {selectModeStr}=this.state;
      this.ModeStr.map((e,index)=>{
        if(e===selectModeStr)guaranteeMode=index+1
      })
    let finInsts=[]
      this.state.selectBank.map((e)=>{
        if(e.selected)finInsts.push(e.name)
      })
    let loanTermLower=1;
    let loanTermUpper=6;
      if(this.selectTimeStr==='1-6个月'){
        loanTermLower=1;
        loanTermUpper=6;
      }else if(this.selectTimeStr==='7-12个月'){
        loanTermLower=7;
        loanTermUpper=12;
      }else if(this.selectTimeStr==='13-24个月'){
        loanTermLower=13;
        loanTermUpper=24;
      }
    let customerId=currentCustomer.id;
    
    // console.log({
    // customerName,orgCode,financingAmount,loanRateLower,loanRateUpper,remark,loanTerm,guaranteeMode,purpose,loanTermLower,loanTermUpper,customerId
    // })
    Taro.showToast({
      title: '正在发布',
      icon: 'none',
      duration: 2000
    })
    Taro.request({
      url: 'http://101.37.65.67/loudi-poc/demand',
      method: 'POST',
      data: {
        customerName,orgCode,financingAmount,loanRateLower,loanRateUpper,remake:remark,loanTerm,guaranteeMode,purpose,loanTermLower,loanTermUpper,customerId
      },
      header: {
        'content-type': 'application/json'
      }
    }).then(res => {
      console.log(res.data)
      Taro.hideToast()
      Taro.navigateTo({
        url:'/pages/publishSuccess/publishSuccess?data='+res.data.data
      })
    })
    
  }
  
  render () {  
    return (
      <View className='wantToFinance_views'>
        <View className='wantToFinance'>
          <View className='title'>发布融资需求</View>
          <View className='content'>
          {/* value='天诚粮食制品有限公司' */}
            <View className='content_item'>企业名称<Input className='name' value={this.state.customerName} disabled={true}/></View>
            <View className='content_item'>组织机构代码<Input className='institution_code' value={this.state.orgCode} disabled={true}/></View>
            <View className='content_item'>融资金额（万元）
              {/* <View className='finnace_money'>￥<Input className='finnace_money_input' placeholder='请输入融资金额' value='2,000'/></View> */}
              <Input className='finnace_money' placeholder='请输入融资金额' value={this.state.financingAmount} onFocus={this.handleFinanceMoneyInputFocus} onBlur={this.handleFinanceMoneyInputBlur} onInput={this.handleFinanceMoneyInput}/>
            </View>
            <View className='content_item'>利率范围 
              <View className='rate_range'>
                <Input className="rate_min" placeholder='%' value={this.state.loanRateLower} onFocus={this.handleRateLowerInputFocus} onInput={this.handleRateLowerInput} onBlur={this.handleRateLowerInputBlur}/>
                至
                <Input className="rate_max" placeholder='%' value={this.state.loanRateUpper} onFocus={this.handleRateUpperInputFocus} onInput={this.handleRateUpperInput} onBlur={this.handleRateUpperInputBlur}/>
              </View>
            </View>
            <View className='content_item'>融资期限（月）<Input className='finance_time' placeholder='请选择融资期限' value={this.state.selectTimeStr} disabled={true} onClick={this.handleSelectFinanceTime}/></View>
            <View className='content_item'>担保方式<Input className='guarrantee_mode' placeholder='请选择担保方式' value={this.state.selectModeStr} disabled={true} onClick={this.handleSelectMode}/></View>
            <View className='content_item'>融资用途<Input className='finance_purpose' placeholder='请选择融资用途' onInput={this.handlePurposeInput}/></View>  
            <View className='banks' disabled={true} onClick={this.handleSelectInsititution}>
              {/* 请选择指定金融机构（选填） */}
              {
                this.state.selectBank.map((bank)=>{
                  if(bank.selected) return <View key={bank.id} className='bank' decode={true} space={true}>{bank.name}<View className='bank_canel'>×</View></View>
                  else return ""
                })
              }
            </View>
            <Textarea className='remark' onInput={this.handleRemarkInput} disabled={this.state.selectTime||this.state.selectMode||this.state.selectPurpose||this.state.selectInsititution} placeholder={this.state.selectTime||this.state.selectMode||this.state.selectPurpose||this.state.selectInsititution?"":'请输入备注（选填）'}></Textarea>  
          </View> 
          <View className='publish_btn' onClick={this.handleFinanceNeedPublish}>立即发布</View>
        </View>

        {/* 日期选择界面 */}
        {this.state.selectTime&&<View className='select_time'>
          <View className='select_time_top' onClick={this.handleCloseAllSelect}></View>
          <View className='select_time_view'>
            <View className='select_handle_bar'>
              <View className='cancel' onClick={this.handleCloseAllSelect}>取消</View>
              <View className='title'>融资期限</View>
              <View className='complete' onClick={this.handleFinishSelectFinanceTime}>完成</View>
            </View>
            <PickerView className='select_items' onChange={this.handleSelectFinanceTimeChange}>
                <PickerViewColumn >  
                  <View>1-6个月</View>
                  <View>7-12个月</View>
                  <View>13-24个月</View>
                </PickerViewColumn> 
            </PickerView>
          </View>
        </View>}
        {/* 担保方式选择界面 */}
        {this.state.selectMode&&<View className='select_mode'>
          <View className='select_top' onClick={this.handleCloseAllSelect}></View>
          <View className='select_view'>
            <View className='select_handle_bar'>
              <View className='cancel' onClick={this.handleCloseAllSelect}>取消</View>
              <View className='title'>担保方式</View>
              <View className='complete' onClick={this.handleFinishSelectMode}>完成</View>
            </View>·
            <PickerView className='select_items' onChange={this.handleSelectModeChange}>
                <PickerViewColumn >
                  <View>抵押</View>
                  <View>质押</View>
                  <View>信保</View>
                  <View>一般保证</View>
                  <View>信用</View>
                </PickerViewColumn> 
            </PickerView>
          </View>
        </View>}
        {/* 融资用途选择界面 */}
        {this.state.selectPurpose&&<View className='select_purpose'>
          <View className='select_top' onClick={this.handleCloseAllSelect}></View>
          <View className='select_view'>
            <View className='select_handle_bar'>
              <View className='cancel'>取消</View>
              <View className='title'>融资用途</View>
              <View className='complete'>完成</View>
            </View>
            <PickerView className='select_items'>
                <PickerViewColumn >
                  <View>抵押</View>
                  <View>质押</View>
                  <View>信保</View>
                  <View>一般保证</View>
                  <View>信用</View>
                </PickerViewColumn> 
            </PickerView>
          </View>
        </View>}
        {/* 金融机构选择界面 */}
        {this.state.selectInsititution&&<View className='select_insititution'>
          <View className='select_insititution_top' onClick={this.handleCloseAllSelect}></View>
          <View className='select_insititution_view'>
            <View className='select_handle_bar'>
              <View className='cancel' onClick={this.handleCloseAllSelect}>取消</View>
              <View className='title'>指定金融机构</View>
              <View className='complete' onClick={this.handleFinishAllSelect}>完成</View>
            </View>
            <View className='select_items'>
              {
                this.state.selectBankTemp.map((bank)=>{
                if(bank.selected) return <View key={bank.id} className='slect_item' onClick={this.handleSelectBankClick} data-index={bank.id}>{bank.name}<Icon size='32rpx' color='#D58F43' type='success_no_circle'></Icon></View>
                  else return <View key={bank.id} className='slect_item' onClick={this.handleSelectBankClick} data-index={bank.id}>{bank.name}<Icon size='32rpx' color='#FFFFFF' type='success_no_circle'></Icon></View>
                })
              } 
            </View> 
          </View>
        </View>}
      </View>
    )
  }
}
